package com.lxm.action;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lxm.entity.ReturnMessage;
import com.lxm.entity.UserEntity;
import com.lxm.entity.query.QuerySenData;
import com.lxm.entity.wx.WxAcceptEntity;
import com.lxm.sevice.User.UserService;
import com.lxm.sevice.sen.PublicSenService;
import com.lxm.sevice.wx.WxService;
import com.lxm.util.Utils;
import com.lxm.util.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author ：Administrator
 * @date :创建时间 2021/12/23 16:06
 */
@Controller
public class WxAction extends ActionBase {

    @Autowired
    private WxService wxService;
    @Autowired
    private PublicSenService publicSenService;
    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate<String, String> auctionRedisTemplate;

    @RequestMapping(value = "/wx", method = RequestMethod.GET)
    @ResponseBody
    public String wxCertification(HttpServletRequest request) {
        // 获取随机数
        String echostr = request.getParameter("echostr");
        // 加密签名
        String signature = request.getParameter("signature");
        //随机数
        String nonce = request.getParameter("nonce");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        // 自己在微信开发那里设置的
        String token = "adfdadfafafasdf";
        List<String> list = new ArrayList<>();
        list.add(token);
        list.add(timestamp);
        list.add(nonce);
        Collections.sort(list);
        String join = String.join("", list);
        String s = DigestUtils.sha1DigestAsHex(join);
        System.out.println(s);
        System.out.println(signature);
        if (s.endsWith(signature)) {
            return request.getParameter("echostr");
        } else {
            return "认证失败";
        }
    }

    @RequestMapping(value = "/wx", method = RequestMethod.POST)
    @ResponseBody
    public String wxGetMessage(@RequestBody String s) throws JsonProcessingException {
        WxAcceptEntity wxAcceptEntity = XmlUtils.stringXmlToBean(s, WxAcceptEntity.class);
        String event = wxAcceptEntity.getEvent();
        String welcome = "欢迎来到蓝小猫推送公众号,推送功能点击下方官网查询,同时公众号接入微软小冰";
        if ("subscribe".equals(event) || "SCAN".equals(event)) {
            wxService.wxLogin(wxAcceptEntity);
            wxAcceptEntity.setContent(welcome);
            wxAcceptEntity.setCreateTime(String.valueOf(new Date().getTime()));
            return wxService.senWxText(wxAcceptEntity);
            //取消公众号
        } else if ("unsubscribe".equals(event)) {

        }
        wxAcceptEntity.setContent(welcome);
        return wxService.senWxText(wxAcceptEntity);
    }


    @RequestMapping(value = "/exitUser/{token}")
    @ResponseBody
    public ReturnMessage exitUser(@PathVariable String token) {
        auctionRedisTemplate.delete(token);
        return success("退出成功");
    }

    @RequestMapping(value = "/senMsg/{authCode}", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMessage senMsgGet(@PathVariable String authCode, QuerySenData querySenData) {
        return publicSenService.PublicSneMsg(authCode, querySenData);
    }

    @RequestMapping(value = "/senMsg/{authCode}", method = RequestMethod.POST)
    @ResponseBody
    public ReturnMessage senMsgPost(@PathVariable String authCode, @RequestBody QuerySenData querySenData) {
        return publicSenService.PublicSneMsg(authCode, querySenData);
    }

    @RequestMapping(value = "/uploadAuthCode/{authCode}")
    @ResponseBody
    public ReturnMessage uploadAuthCode(@PathVariable String authCode) {
        ValueOperations<String, String> stringStringValueOperations = auctionRedisTemplate.opsForValue();
        String UserString = stringStringValueOperations.get(authCode);
        if (UserString != null && UserString.isEmpty()) {
            return error("数据异常");
        }
        JSONObject jsonObject = JSONObject.parseObject(UserString);
        String info = jsonObject.getString("info");
        UserEntity userEntity = JSONObject.parseObject(info, UserEntity.class);
        UserEntity updata = new UserEntity();
        updata.setId(userEntity.getId());
        updata.setAuthCode(Utils.getAuthCode());
        userService.updateById(updata);
        userEntity.setAuthCode(updata.getAuthCode());
        jsonObject.put("info",userEntity);
        stringStringValueOperations.set(authCode,jsonObject.toJSONString(),1, TimeUnit.HOURS);
        return success("更新成功");
    }

    @RequestMapping(value = "/getUserInfo/{token}", method = RequestMethod.GET)
    @ResponseBody
    public String getUserInfo(@PathVariable String token) {
        ValueOperations<String, String> stringStringValueOperations = auctionRedisTemplate.opsForValue();
        String token1 = stringStringValueOperations.get(token);
        System.out.println(token1);
        return token1;
    }

    @RequestMapping(value = "/getQrcode")
    @ResponseBody
    public String getQrcode() {
        String qrcode = wxService.getQrcode();
        return qrcode;
    }
}
